
const fs = require("fs");
const url = require("url");
const FormData = require("form-data");
const buffer = require("buffer");
const path = require("path");
const util = require("util");
const http = require("http");

const get_token = require("./get-token");

const upload_url = "http://upload.qiniu.com/";
const parsed = url.parse(upload_url);

/**
 * 
 * @param {ReadableStream} stream 
 * @param {Strings} ext 
 * @returns {Promise<{ok:Boolean,msg:String,url:String}>}
 */
function uploadFileStream(stream, ext = "part0") {
    return new Promise(async resolve => {
        let o_getToken = await get_token.getUploadToken(`${ext}`);
        if (!o_getToken.ok) {
            return resolve({
                ok: false,
                msg: `error when getUploadToken():${o_getToken.msg}`,
                url: ''
            })
        }
        let token = o_getToken.token;
        let remote_filename = o_getToken.remote_filename;
        let form = new FormData;
        form.append("file", stream, {
            filename: `${Math.random()}.${ext}`
        });
        form.append("key", remote_filename);
        form.append("token", token);
        let headers = {
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36",
            "Referer": "http://pianke.me/editor/",
            'X-Requested-With': 'XMLHttpRequest',
        };
        let request = http.request({
            method: "POST",
            host: parsed.host,
            path: parsed.path,
            headers: {
                ...form.getHeaders(),
                ...headers
            }
        });
        form.on("error", err => {
            resolve({
                ok: false,
                msg: `form.on(error):${err.message}`,
                url: ""
            })
        });
        form.pipe(request);
        request.on("response", (resp) => {
            let buf = new buffer.Buffer("");
            resp.on("data", chunk => {
                buf += chunk;
            })
            resp.on("end", $ => {
                try {
                    let obj = JSON.parse(buf);
                    let file_url = `https://qnimg.pianke.me/${obj['key']}`;
                    resolve({
                        ok: true,
                        msg: "ok",
                        url: file_url
                    })
                } catch (e) {
                    resolve({
                        ok: false,
                        url: "",
                        msg: `error when try extract url :${e.message ? e.message : util.inspect(e)}`
                    })
                }
            })
        });
        request.on("error", err => {
            resolve({
                ok: false,
                msg: `request.on(error):${err.message}`,
                url: ""
            })
        });
    })
}

module.exports = {
    uploadFileStream:uploadFileStream
}